package com.ifcar.app.util;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.ifcar.app.rss.GetColumnsInfo;

public class StringUtil {
	
	public static final String OFFLINEUPDATE = "com.ifcar.app.offlineupdate";
    
    public static final String userAgent = "NTES Android";
	/**
	 * 新闻每次加载的初始条数
	 */
	public static final int perTimeNumber = 20;
	/**
	 * 话题URL
	 */
	public static final String topic_url = "http://c.3g.163.com/nc/article/attitude/"; // ${start}-${length}.html;
	public static final String topic_url_detailpage = "http://c.3g.163.com/nc/article/";
	/**
	 * 图集API
	 */
	/*public static final String PHOTOSETINFOURL = "http://c.3g.163.com/photo/api/set/0096/";
	public static final String PHOTOSETLISTURL = "http://c.3g.163.com/photo/api/list/0096/4GJ60096";
	public static final String PHOTOSETNEWLISTURL = "http://c.3g.163.com/photo/api/newlist/0096/4GJ60096/";
	public static final String PHOTOSETMORELISTURL = "http://c.3g.163.com/photo/api/morelist/0096/4GJ60096/";*/
	
	public static final String PHOTOSETINFOURL = "http://c.3g.163.com/photo/api/set/%s/%s.json";
    public static final String PHOTOSETLISTURL = "http://c.3g.163.com/photo/api/list/%s/%s.json";
    public static final String PHOTOSETNEWLISTURL = "http://c.3g.163.com/photo/api/newlist/%s/%s/%s.json";
    public static final String PHOTOSETMORELISTURL = "http://c.3g.163.com/photo/api/morelist/%s/%s/%s.json";
	/**
	 * 通行证登录和分享到微博
	 */
	public static final String SSLXURL = "https://reg.163.com/logins.jsp";
	public static final String SHARETOMICROBLOG = "http://api.t.163.com/statuses/update.json";
	public static final String NEWSCLIENTSOURCE = "<a href=\"http://m.163.com/newsapp/\">网易Android新闻客户端</a>";
	public static final String FEEDBACKURL = "http://3g.163.com/bbs/bbs_news/3g/feedback.do";//反馈URL
	
	/**注册URL*/
	public static final String REGISTERURL = "http://c.3g.163.com/urs/reg";
	
	/**公告URL*/
	public static final String NOTICEURL = "http://m.163.com/special/newsclient/android_notice.html?"+System.currentTimeMillis();
	//public static final String NOTICEURL = "http://m.163.com/special/newsclient/notice_test.html?"+System.currentTimeMillis();
	/**
	 * 跟贴URL规整
	 */
	//http://comment.news.163.com/%@/%@[/%@].html",board,docID,selectedFloorID
	public static final String TIEURL = "http://comment.news.163.com/";
	/**
	 * 获得某层楼的图片快照端地址
	 * http://webshot.ws.126.net/%@/%@/%@.html
	 */
	public static final String TIEFLOORSHORTURL = "http://webshot.ws.126.net/";
	/**
	 * PUSH URL
	 */
	public static final String NEW_PUSHURL = "http://p.3g.163.com/push/newsclient/";
	public static final String LAST_PUSHURL = "http://p.3g.163.com/nc/last.do";
	public static final String NOW_PUSHURL = "http://p.3g.163.com/nc/now.do";
	/*public static final String LAST_PUSHURL = "http://220.181.8.135:8080/nc/last.do";
    public static final String NOW_PUSHURL = "http://220.181.8.135:8080/nc/now.do";*/
	
	/**
	 * 投票列表URL
	 */
	public static String voteList_url = "http://c.3g.163.com/nc/vote/init/all.html";//"http://c.3g.163.com/nc/vote/init/list.html";//"";
	/**
	 * 查看以往投票 
	 */
	public static String voteOld_url = "http://c.3g.163.com/nc/vote/result/";//"http://c.3g.163.com/nc/vote/result/";
	/**
	 * 提交投票
	 */
	public static String voteSubmit_Url = "http://vote.3g.163.com/vote2/mobileVote.do?vote";
	/**
	 * 图片缩放地址
	 */
	public static String imageResize_Url = "http://s.cimg.163.com/i/";
	/**
	 * 话题
	 */
	public static final String IS_TOPIC = "is_topic"; // 标记投票
	
    public static final String TOPIC_DOCID = "docid"; // 文章ID
	public static final String TOPIC_TITLE = "title"; // 文章标题
	public static final String TOPIC_SUBTITLE = "subtitle"; // 副标题
	public static final String TOPIC_PTIME = "ptime"; // 发表时间
	public static final String TOPIC_URL = "url"; // 文章URL
	public static final String TOPIC_IMGSRC = "imgsrc"; // 第一条有配图
	public static final String TOPIC_SPECIAL_ID = "speciaID";
	public static final String TOPIC_DIGEST = "digest"; //概述
    /*评论栏目ID*/
    public static final String COLUMN_TOPIC_COMMENT = "T1334130148846";
    /*博客栏目ID*/
    public static final String COLUMN_TOPIC_BLOG = "T1334130296157";
    /*论坛栏目ID*/
    public static final String COLUMN_TOPIC_BBS = "T1334130320521";
	/*独家解读栏目ID*/
    public static final String COLUMN_TOPIC_DUJIA = "T1336528929188";
    /*另一面栏目ID*/
    public static final String COLUMN_TOPIC_ANOTHER = "T1336528712077";
    /*专业控栏目ID*/
    public static final String COLUMN_TOPIC_SPECIALI = "T1336528876783";
    /*数读栏目ID*/
    public static final String COLUMN_TOPIC_DIGIT = "T1336528754726";
    
	/**
	 * 投票 字段	
	 */
	public static final String VOTE_ITEM_ID = "id"; // 选项ID
	public static final String VOTE_ITEM_NUM = "num"; // 选项个数
	public static final String VOTE_ITEM_NAME = "name"; // 选项名称
	
	public static final String VOTE_ID = "vote_id";
	public static final String VOTE_IMGSRC = "imgsrc"; // 图片
	public static final String VOTE_DIGEST = "digest"; // 描述
	public static final String VOTE_QUESTION = "question"; // 问题
	public static final String VOTE_DATE = "date"; // 问题
	public static final String VOTE_DOCID = "docid";
	// 相关列表
	public static final String VOTE_ITEM_LIST = "voteitem"; // 投票选项
	public static final String VOTE_ID_LIST = "voteidlist"; // 投票ID列表
	public static final String ALREADY_VOTE = "already_vote";
	/**
	 * 话题投票
	 */
	public static final String TOPIC = "attitude"; // 话题
	public static final String VOTE = "vote"; // 投票
	
	//跟帖
	public static final String TOP_COMMENTS_CONTENT = "top_comments_content"; 
	public static final String TOP_COMMENTS_SOURCE = "top_comments_source"; 
	
	public static final String COMMENTS_REPLY_COUNT = "reply_count"; 
	public static final String RANK_COMMENTS_SOURCE = "rank_comments_source"; 
	
	public static final String COMMENT_TYPE = "comment_type";
	public static final String HOT_COMMENT = "hot";
	public static final String NEW_COMMENT = "new";
	public static final String BUILDING_ID = "building_id";
	public static final String COMMENT_COLUMN_ID = "comment_column_id";
	
	public static final int maxBuildingNum = 10;
	public static final int HotCommentsNum = 5;
	public static final int LatestCommentsNum = 5;
	public static final int LatestCommentsNumInOriginal = 10;
	
	public final static int HEAD_TYPE = 0;
	public final static int NONHEAD_TYPE = 1;
	public final static int TOPIC_TYPE = 2;
	public final static int SPECIAL_TYPE = 3; 
	
	public final static int PAGE_UP_TYPE = 1; //往前翻
	public final static int PAGE_DOWN_TYPE = 2; //往后翻
	
	public final static String PREFERENCE_SPECIAL_BANNER = "banner";//专题的头图
	
	/**
	 * 返回 format 格式的时间字符串
	 * 时间格式为 yyyy-MM-dd HH:mm:ss
	 * yyyy 返回4位年份
	 * MM 返回2位月份
	 * dd 返回2位日
	 * 时间类同
	 * @return 相应日期类型的字符串
	 */
	public static String getCurrnetDate(String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date()).toString();
	}

	/**
	 * 获取整除结果 
	 * @param itemNum
	 * @param allVoteNum
	 * @return
	 */
	public static float getPercent(int itemNum, long allVoteNum) {
		float p = (float)itemNum/allVoteNum;
		
		DecimalFormat df = new DecimalFormat("0.00");//格式化小数，不足的补0
		String s = df.format(p);
		float f = Float.parseFloat(s);

		return f;
	}
	
	/**
	 * 获取当前时间的 小时和秒
	 * @param date
	 * @return
	 */
	public static String getHourSecond(Date date){
		
		String fomat = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat dfs = new SimpleDateFormat(fomat);  
		String rst = dfs.format(date);
		
		return rst.substring(10,15);
	}
	
	/**
	 * 获取何时已经刷新的时间
	 * @param refreshTime
	 * @return
	 */
    public static String getDateForRefresh(long refreshTime) {
        String date = "";
        try {
            Date begin = new Date(refreshTime);  
            Date end = new Date();
            long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒  
            
            long day=between/(24*3600);  
            long hour=between%(24*3600)/3600;  
            long minute=between%3600/60;  
            long second=between%60/60;
            
            if(day>=1){
                date =  new SimpleDateFormat("MM月dd日").format(begin);
            }else if(hour>0 && day == 0){
                date = hour + "小时前";
            }else if(minute>0 && hour==0 && day == 0){
                date = minute + "分钟前";
            }/*else if(second>0 && minute==0&&hour==0 && day == 0){
                date = second + "秒前";
            }*/else {
                date = "1分钟前";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(date)) {
            return date + "更新";
        }
        return "";
    }
	
	/**
	 * 获取时间差
	 * @param date
	 * @return
	 */
	public static String getDate(String date) {
		if(null==date || "".equals(date)){
			return "";
		}
		String fomat = "yyyy-MM-dd HH:mm:ss";
		try {
			SimpleDateFormat dfs = new SimpleDateFormat(fomat);  
			Date begin=dfs.parse(date);  
			Date end = dfs.parse(StringUtil.getCurrnetDate(fomat));
			long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒  
			
			long day=between/(24*3600);  
			long hour=between%(24*3600)/3600;  
			long minute=between%3600/60;  
			long second=between%60/60;
			
			if(day>=1){
				date =  new SimpleDateFormat("yyyy-MM-dd").format(begin);
			}else if(hour>0 && day == 0){
				date = hour + "小时前";
			}else if(minute>0 && hour==0 && day == 0){
				date = minute + "分钟前";
			}/*else if(second>0 && minute==0&&hour==0 && day == 0){
				date = second + "秒前";
			}*/else {
				date = "1分钟前";
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return date;
	}
	
	/**
	 * 获取时间差
	 * @param date
	 * @param format
	 * @return
	 */
	public static String getDate(String date, String format) {
		try {
			SimpleDateFormat dfs = new SimpleDateFormat(format);  
			Date begin=dfs.parse(date);  
			Date end = dfs.parse(StringUtil.getCurrnetDate(format));
			long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒  
			
			long day=between/(24*3600);  
			long hour=between%(24*3600)/3600;  
			long minute=between%3600/60;  
			long second=between%60/60;
			
			if(day>=1){
				date =  new SimpleDateFormat("yyyy-MM-dd").format(begin);
			}else if(hour>0 && day == 0){
				date = hour + "小时前";
			}else if(minute>0 && hour==0 && day == 0){
				date = minute + "分钟前";
			}else if(second>0 && minute==0&&hour==0 && day == 0){
				date = second + "秒前";
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	
	/**
	 * 时间大小比较
	 * @param endDate
	 * @param beginDate
	 * @return
	 */
	public static boolean compareDate(String endDate, String beginDate) {
		String fomat = "yyyy-MM-dd HH:mm:ss";
		try {
			SimpleDateFormat dfs = new SimpleDateFormat(fomat);  
			Date begin=dfs.parse(beginDate);  
			Date end = dfs.parse(endDate);
			long between=(end.getTime()-begin.getTime());  

            if(between>0){
				return true;
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return false;
	}
	
	/**
	 * 判断图片地址合法性
	 * */
	public static boolean isExactPicUrl(String imgUrl){		
		return (imgUrl.endsWith(".jpg") || imgUrl.endsWith(".gif") || imgUrl.endsWith(".png")|| imgUrl.endsWith(".jpeg"));
	}
	
	
    /**
     * base64 编码  指定字符集charset
     * @param str
     * @param charset
     * @return
     */
    public static String base64Encode(String str, String charset) {
        try {
            if(null == str)
                return "";
            return it.sauronsoftware.base64.Base64.encode(str, charset);
        } catch (RuntimeException e) {
            return str;
        }
    }
    
    /**
     * URL编码
     * 
     * @param str
     * @return
     */
    public static String URLEncode(String str) {
        try {
            if(null == str)
                return "";
            
            return URLEncoder.encode(str, "utf-8");
        } catch (Exception e) {
            return "";
        }
    }
    
    /**
     * 通用编码
     * 
     * @param str
     * @return
     */
    public static String encode(String str) {
        try {
            str = base64Encode(str, "utf-8");
            return URLEncode(str);
        } catch (Exception e) {
            return str;
        }
    }
    
    /**
     * socket 异常处理
     * @param str
     * @return
     */
    public static String replaceEnter(String str) {
        str = str.replace("'", "");
        return str.replace('\n',' ');
    }
    /**
     * socket 异常事件截取
     * @param param
     * @return
     */
    public static String valideEventParam(String param) {
        if(null!=param){
            if(param.length() > 64) {
                param = param.substring(0, 63);
            }
            return replaceEnter(param);
        }else{
            return "nodefine";
        }
        
    }
    
    private static final long MIN = 60 * 1000;

   /**
    * 判断是否需要刷新
    * @param context
    * @param key
    * @param min
    * @return
    */
    public static boolean isNeedRefresh(Context context, String key, int min) {
        if (TextUtils.isEmpty(key)) {
            return false;
        }
        SharedPreferences sp = context
                .getSharedPreferences("refresh_time_sp", Context.MODE_PRIVATE);
        long lastRefreshTime = sp.getLong(key, -1);
        if (lastRefreshTime == -1 || System.currentTimeMillis() - lastRefreshTime >= (min * MIN)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 超过30分钟后需要刷新---用户新闻列表
     * @param context
     * @param key
     * @return
     */
    public static boolean isNeedRefresh(Context context, String key) {
        return isNeedRefresh(context, key, 30);
    }
    
    /**
     * 超过12小时需要再次离线下载
     * @param context
     * @return
     */
    public static boolean isNeedOfflineDownload(Context context) {
        return isNeedRefresh(context, "autoDownTime", 12*60);
    }
    
    /**
     * 离线后30分钟，在网络的情况下不再提示网络失败
     * @param context
     * @return
     */
    public static boolean isTipsAfterOfflineDownload(Context context){
        return isNeedRefresh(context,"autoDownTime",120);
    }
    
    public static void clearOfflineDownloadRefreshTime(Context context){
        clearRefreshTime(context,"autoDownTime");
    }
    
    /**
     * 更新刷新时间
     * @param context
     * @param key
     */
    public static void updateRefreshTime(Context context, String key) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        SharedPreferences sp = context
                .getSharedPreferences("refresh_time_sp", Context.MODE_PRIVATE);
        sp.edit().putLong(key, System.currentTimeMillis()).commit();
    }
    
    /**
     * 获取刷新时间
     * @param context
     * @param key
     * @return
     */
    public static String getRefreshTimeStr(Context context, String key) {
        if (TextUtils.isEmpty(key)) {
            return "";
        }
        SharedPreferences sp = context
                .getSharedPreferences("refresh_time_sp", Context.MODE_PRIVATE);
        String refreshStr;
        long lastRefresh = sp.getLong(key, -1);
        if (lastRefresh == -1) {
            refreshStr = "";
        } else {
            refreshStr = StringUtil.getDateForRefresh(lastRefresh);
        }
        return refreshStr;
    }
    
    /**
     * 清空刷新时间
     * @param context
     * @param key
     */
    public static void clearRefreshTime(Context context, String key) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        SharedPreferences sp = context
                .getSharedPreferences("refresh_time_sp", Context.MODE_PRIVATE);
        sp.edit().remove(key).commit();
    }
    
    /**
     * 日间or夜间文章正文内嵌图片JavaScript代码片段
     * @param theme ture 日间模式  false 夜间模式
     * @param docid
     * @return
     */
    
    public static String displayPicInDoc(boolean theme,int currnetpic,String localpic,String docid){
        String js = "";
        String show_hide = "display:none;";
        String onclick = "zoomOut("+ currnetpic +"); ";
        if(null==localpic || "".equalsIgnoreCase(localpic)){
            show_hide = "display:none;";
        }else{
            show_hide = "display:block;";
        }
        if(theme){
            js = "<div style=\"background-image:url(detailpage_image_bk.png);" +
            "width:115px;height:105px;float:right;clear:right;overflow:hidden;margin-top:10px;\">" + 
            "<a href=\"javascript:void(0)\" id=\"imgcontent"+currnetpic+"_"+docid+"\" onclick=" +onclick +
            "style=\"background-image:url("+localpic+");display:block;" +
            "width:100px;height:100px;margin-left:12px;margin-right:1px;margin-top:0px;margin-bottom:2px\" >" +
            "</a><img id=\"largepic"+currnetpic+"\" onclick="+onclick+" src=\"add.png\" style=\"width:20px;height:20px;border:none;margin-left:3px;margin-top:-17px;"+show_hide+"\" ></img></div>";
        }else{
            js =  "<div style=\"background-image:url(night_detailpage_image_bk.png);" +
            "width:115px;height:105px;float:right;clear:right;overflow:hidden;margin-top:10px;\">" + 
            "<a href=\"javascript:void(0)\" id=\"imgcontent"+currnetpic+"_"+docid+"\" onclick=" +onclick +
            "style=\"background-image:url("+localpic+");display:block;opacity:0.5;" +
            "width:100px;height:100px;margin-left:12px;margin-right:1px;margin-top:0px;margin-bottom:2px\" >" +                                     
            "</a><img id=\"largepic"+currnetpic+"\" onclick="+onclick+"  src=\"add.png\" style=\"width:20px;height:20px;border:none;margin-left:3px;margin-top:-17px;opacity:0.6;"+show_hide+"\" ></img></div>";
        }
        return js;
    }
    
    /**
     * 将获得的图片渲染到文章中
     * @param currnetpic
     * @param localpic
     * @param docid
     * @return
     */
    public static String applyPicToDoc(int currnetpic,String localpic,String docid){
        return "javascript:(function() {"
        +"$('#largepic"+
        currnetpic+"').show();"
        + "$('#imgcontent"
        + currnetpic+"_"+docid
        + "').css('background-image',"
        + "\"url("
        + localpic + ")\");})()";
    }

   public static String delSpaceStr(String str) {  
	        
		if (str == null) {  
			return str;  
		}  
		
		String regStartSpace = "^[　 ]*";  
		String regEndSpace = "[　 ]*$";  
		
		String strDelSpace = str.replaceAll(regStartSpace, "").replaceAll(regEndSpace, "");  
		
		return strDelSpace;  
    }  
   
   public static String findMicrohotAthor(String text, boolean isContainAt){
       String regEx = "@([\u4e00-\u9fa5A-Za-z0-9_-]*)?";
       Pattern p=Pattern.compile(regEx);
       Matcher m=p.matcher(text);
       
       String author = "";
       int i = 0;
       while(i==0 && m.find()) {
           author = m.group();
           i++;
       }
       
       return isContainAt ? author : author.replace("@", "");
	}
   
   /**
    * 查找 regex 在 string 中出现的次数
    * @param string
    * @param regex
    */
    public static int findRegexCount(StringBuilder string, String regex) {
    	
    	Pattern pt = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    	Matcher mc = pt.matcher(string);
    	int count = 0;
    	while (mc.find()) {
        	++ count;
    	}
    	if(count % 2 != 0) return count;
    	
    	replaceSpace(string, regex);
    	
    	return count;
    }
    
    private static void replaceSpace(StringBuilder str, String tag){
		Matcher mc = Pattern.compile(tag).matcher(str);
		mc = Pattern.compile(tag).matcher(str);
		while (mc.find()) {
			int index;
			try {
				index = mc.start();
			} catch (Exception e1) {
				break;
			}
			
			while(true){
				try {
					if(--index < 0) break;
					
					char s = str.charAt(index);
					
					boolean isspace = isSpaceChar(s);
					
					if(isspace){
						str.replace(index, index + 1, "");
						mc = Pattern.compile(tag).matcher(str);
					} else {
						break;
					}
				} catch (Exception e) { 
					e.printStackTrace();
					break;
				}
				
			}
			
		}
	}
    

   /**
	 * 判断空白字符串
	 * @param str
	 * @return
	 */
	private static boolean isSpaceChar(char str){
		String regex = "^\\s*$";
       Pattern pt = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher mac = pt.matcher(String.valueOf(str));
		return mac.find();
	}
   
   /**
    * 拼接翻页数据
    * @param list
    * @return
    */
   public static String createIdString(List<Map<String, Object>> list) {
	   if(null == list || list.size() <= 0) return null;
	   JSONArray array = new JSONArray();
	   for(Map<String, Object> map : list){
		   if(null != map.get(GetColumnsInfo.DOCID_TAG)){
			   String id = (String)map.get(GetColumnsInfo.DOCID_TAG);
			   array.put(id);
		   }
	   }
	   return array.toString();
   }
   
   
   public static String GetString(Object parm)
   {
       if(parm!=null)
       {
           return parm.toString();
       }
       else return "";
   }
}
